import 'dart:convert' show json;

import 'package:flutter/cupertino.dart';

T asT<T>(dynamic value) {
  if (value is T) {
    return value;
  }
  return null;
}

class DissolutionEntity with ChangeNotifier {
  DissolutionEntity({
    this.dissolutionStartDate,
    this.dissolutionRemainingDate,
    this.remainingTime,
    this.userDissolution,
  });

  void update(DissolutionEntity entity) {
    this.remainingTime = entity.remainingTime;
    this.dissolutionRemainingDate = entity.dissolutionRemainingDate;
    this.dissolutionStartDate = entity.dissolutionStartDate;
    this.userDissolution = entity.userDissolution;
    notifyListeners();
  }

  factory DissolutionEntity.fromJson(Map<String, dynamic> jsonRes) {
    if (jsonRes == null) {
      return null;
    }
    Map<String, UserDissolution> userDissolution;
    var userDissolutionData = jsonRes['userDissolution'];
    if (userDissolutionData != null && userDissolutionData is Map) {
      userDissolution = {};
      var userDissolutionTemp = Map.castFrom(jsonRes["userDissolution"]);
      userDissolutionTemp.forEach((key, value) {
        var userInfo = UserDissolution.fromJson(Map.castFrom(value));
        userDissolution[key] = userInfo;
      });
    }
    return DissolutionEntity(
      dissolutionStartDate: asT<String>(jsonRes['dissolutionStartDate']),
      dissolutionRemainingDate:
          asT<String>(jsonRes['dissolutionRemainingDate']),
      remainingTime: asT<int>(jsonRes['remainingTime']),
      userDissolution: userDissolution,
    );
  }

  String dissolutionStartDate;
  String dissolutionRemainingDate;
  int remainingTime;
  Map<String, UserDissolution> userDissolution;

  Map<String, dynamic> toJson() => <String, dynamic>{
        'dissolutionStartDate': dissolutionStartDate,
        'dissolutionRemainingDate': dissolutionRemainingDate,
        'remainingTime': remainingTime,
        'userDissolution': userDissolution,
      };

  @override
  String toString() {
    return json.encode(this);
  }
}

class UserDissolution {
  UserDissolution({
    this.username,
    this.portraitUrl,
    this.agreeState,
  });

  factory UserDissolution.fromJson(Map<String, dynamic> jsonRes) =>
      jsonRes == null
          ? null
          : UserDissolution(
              username: asT<String>(jsonRes['username']),
              portraitUrl: asT<String>(jsonRes['portraitUrl']),
              agreeState: asT<int>(jsonRes['agreeState']),
            );

  String username;
  String portraitUrl;
  int agreeState;

  Map<String, dynamic> toJson() => <String, dynamic>{
        'username': username,
        'portraitUrl': portraitUrl,
        'agreeState': agreeState,
      };

  @override
  String toString() {
    return json.encode(this);
  }
}
